package cn.edu.henu.team.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.Rotate;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import androidx.appcompat.app.AlertDialog;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.utils.myImageLoader;

public class UserMessageActivity extends BaseActivity {

    private ImageView back;
    private ProgressBar progress;
    private AlertDialog.Builder alertDialog;
    private AlertDialog.Builder alertDialog_2;
    private AlertDialog.Builder alertDialog_3;
    private AlertDialog.Builder alertDialog_4;
    private ArrayList<ImageItem> imageItems;
    // 显示头像
    private ListView listView_1;
    private List<Map<String,Object>> data_1 = new ArrayList<>();
    private SimpleAdapter simpleAdapter;
    // 显示其余信息
    private String path = null;
    private ListView listView_2;
    private List<Map<String,Object>> data_2 = new ArrayList<>();
    private SimpleAdapter simpleAdapter_2;
    private String name;
    private String telephone;
    private String brief_intro_text;
    private String addressMsg;
    private String brief_intro = "点击修改";
    private String psw = "点击修改";
    private String cover = "点击修改";

    @Override
    protected int initLayout() {
        return R.layout.activity_user_message;
    }

    @Override
    protected void initView() {
        back = findViewById(R.id.back);
        progress =  findViewById(R.id.progress);

        listView_1 = findViewById(R.id.listview_1);
        listView_2 =  findViewById(R.id.listview_2);
        listView_2.addHeaderView(new ViewStub(this));//顶部分割线
        listView_2.addFooterView(new ViewStub(this));//底部分割线
    }

    @Override
    protected void initData() {
        // 根据ID查询单条数据
        _User current_user = BmobUser.getCurrentUser(_User.class);
        // 获得图片地址url
        BmobFile now_user_img = current_user.getHeadPortrait();
        String now_user_img_url = now_user_img.getFileUrl();
        // 获得信息
        name = current_user.getNickName().toString();
        if (current_user.getBrief_intro() == null || current_user.getBrief_intro().equals("")) {
            brief_intro_text = "这个人很懒，什么也没留下...";
        } else
            brief_intro_text = current_user.getBrief_intro().toString();
        telephone = current_user.getMobilePhoneNumber().toString();
        addressMsg = current_user.getAddressMsg();

        // 用户头像实例化
        Map<String,Object> temp_1 = new LinkedHashMap<>();
        temp_1.put("text", "头像");
        temp_1.put("message_image", now_user_img_url);
        data_1.add(temp_1);
        simpleAdapter = new SimpleAdapter(this, data_1, R.layout.user_message_item, new String[] {"text","message_image"}, new int[] {R.id.text, R.id.message_image});
        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            public boolean setViewValue(View view, Object data,
                                        String textRepresentation) {
                //判断是否为我们要处理的对象
                if(view instanceof ImageView  && data instanceof String){
                    ImageView iv = (ImageView) view;
                    Glide.with(UserMessageActivity.this).load(now_user_img_url).transform(new Rotate(0)).into(iv);
                    return true;
                }else
                    return false;
            }
        });
        listView_1.setAdapter(simpleAdapter);

        // 用户信息实例化
        String[] user_message = new String[] {"昵称","简介","账号","密码","个人主页封面","当前位置信息"};
        String[] message_text = new String[] {name,brief_intro,telephone,psw,cover,addressMsg};
        for (int i = 0; i < 6; i++) {
            Map<String,Object> temp_2 = new LinkedHashMap<>();
            temp_2.put("text",user_message[i]);
            temp_2.put("message_text",message_text[i]);
            data_2.add(temp_2);
        }
        simpleAdapter_2 = new SimpleAdapter(this, data_2, R.layout.user_message_item_2, new String[] {"text","message_text"}, new int[] {R.id.text, R.id.message_text});
        listView_2.setAdapter(simpleAdapter_2);

        clickEvents();
    }

    public void clickEvents() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        listView_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (arg2 == 0) {
                    //打开相册进行选择
                    addHeaderImg();
                }
            }
        });

        listView_2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //这里的item是从1算起而不是0
                if (arg2 == 1) {
                    creatDialog();
                    alertDialog.show();
                }
                if (arg2 == 2) {
                    creatDialog_2();
                    alertDialog_2.show();
                }
                if (arg2 == 3) {
                    creatDialog_3();
                    alertDialog_3.show();
                }
                if (arg2 == 4) {
                    creatDialog_4();
                    alertDialog_4.show();
                }
                if (arg2 == 5) {
                    //打开相册进行选择
                    addBGImg();
                }
            }
        });

    }

    public void creatDialog() {
        final EditText et = new EditText(UserMessageActivity.this);
        et.setHint(name);
        et.setSingleLine(true);
        //先设置好点击“修改昵称”弹出的dialog
        alertDialog = new AlertDialog.Builder(this);
        alertDialog.setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "昵称不能为空哦", Toast.LENGTH_SHORT).show();
                        } else {
                            name = input;
                            // 修改后端的用户昵称
                            _User current_user = BmobUser.getCurrentUser(_User.class);
                            current_user.setNickName(name);
                            current_user.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null){
                                        Toast.makeText(getApplication(), "昵称更换成功", Toast.LENGTH_SHORT).show();
                                    }else {
                                        Toast.makeText(getApplication(), "昵称更换失败", Toast.LENGTH_SHORT).show();
                                    }
                                    // 修改界面的用户昵称
                                    refresh();
                                }
                            });
                        }

                    }
                })
                .setNegativeButton("取消", null).create();
    }

    public void creatDialog_2() {
        final EditText et = new EditText(UserMessageActivity.this);
        et.setHint(brief_intro_text);
        //先设置好点击“修改昵称”弹出的dialog
        alertDialog_2 = new AlertDialog.Builder(this);
        alertDialog_2.setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "简介不能为空哦", Toast.LENGTH_SHORT).show();
                        } else {
                            brief_intro_text = input;
                            _User current_user = BmobUser.getCurrentUser(_User.class);
                            current_user.setBrief_intro(brief_intro_text);
                            current_user.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null){
                                        Toast.makeText(getApplication(), "简介修改成功", Toast.LENGTH_SHORT).show();
                                    }else {
                                        Toast.makeText(getApplication(), "简介修改失败", Toast.LENGTH_SHORT).show();
                                    }
                                    refresh();
                                }
                            });
                        }

                    }
                })
                .setNegativeButton("取消", null).create();
    }

    public void creatDialog_3() {
        final EditText et = new EditText(UserMessageActivity.this);
        et.setHint("请输入新的手机号");
        //先设置好点击“修改昵称”弹出的dialog
        alertDialog_3 = new AlertDialog.Builder(this);
        alertDialog_3.setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "手机号不能为空哦", Toast.LENGTH_SHORT).show();
                        } else {
                            telephone = input;
                            _User current_user = BmobUser.getCurrentUser(_User.class);
                            current_user.setUsername(telephone);
                            current_user.setMobilePhoneNumber(telephone);
                            current_user.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null){
                                        Toast.makeText(getApplication(), "手机号修改成功", Toast.LENGTH_SHORT).show();
                                    }else {
                                        Toast.makeText(getApplication(), "手机号修改失败", Toast.LENGTH_SHORT).show();
                                    }
                                    refresh();
                                }
                            });
                        }

                    }
                })
                .setNegativeButton("取消", null).create();
    }

    public void creatDialog_4() {
        final EditText et = new EditText(UserMessageActivity.this);
        et.setHint("请输入新的密码");
        //先设置好点击“修改昵称”弹出的dialog
        alertDialog_4 = new AlertDialog.Builder(this);
        alertDialog_4.setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "手机号不能为空哦", Toast.LENGTH_SHORT).show();
                        } else {
                            String password = input;
                            _User current_user = BmobUser.getCurrentUser(_User.class);
                            current_user.setPassword(password);
                            current_user.update(new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null){
                                        Toast.makeText(getApplication(), "密码修改成功", Toast.LENGTH_SHORT).show();
                                    }else {
                                        Toast.makeText(getApplication(), "密码修改失败", Toast.LENGTH_SHORT).show();
                                    }
                                    refresh();
                                }
                            });
                        }

                    }
                })
                .setNegativeButton("取消", null).create();
    }

    /**
     * 添加头像哦
     */
    private void addHeaderImg() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(1);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(UserMessageActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    /**
     * 添加封面背景
     */
    private void addBGImg() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(1);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(UserMessageActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 200);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                String url = filePaths[0];
                Log.d("path",url);
                uploadImage(url);
            }else if(data != null && requestCode == 200) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                String url = filePaths[0];
                Log.d("path",url);
                uploadCoverPage(url);
            } else {
                showToastInThread(getApplicationContext(),"没有选择图片呢! ");
            }
        }
    }

    /**
     * 将图片上传到 Bmob
     */
    public void uploadImage(String url) {
        final BmobFile file = new BmobFile(new File(url));
        progress.setVisibility(View.VISIBLE);
        file.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    //Toast.makeText(getApplication(), "上传成功", Toast.LENGTH_SHORT).show();
                    _User current_user = BmobUser.getCurrentUser(_User.class);
                    current_user.setheadPortrait(file);
                    current_user.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null){
                                Toast.makeText(getApplication(), "头像更换成功", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(getApplication(), "头像更换失败", Toast.LENGTH_SHORT).show();
                            }
                            // 更换头像
                            refresh();
                        }
                    });
                } else {
                    Toast.makeText(getApplication(), "上传失败", Toast.LENGTH_SHORT).show();
                }
                progress.setVisibility(View.GONE);
            }
        });
    }

    public void uploadCoverPage(String uri) {
        final BmobFile image_file = new BmobFile(new File(uri));
        //要先上传图片，之后才能将图片加载到新建数据列里
        progress.setVisibility(View.VISIBLE);
        image_file.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    _User current_user = BmobUser.getCurrentUser(_User.class);
                    current_user.setCoverPage(image_file);
                    current_user.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null){
                                progress.setVisibility(View.GONE);
                                Toast.makeText(getApplication(), "个人主页封面更换成功", Toast.LENGTH_SHORT).show();
                            }else {
                                progress.setVisibility(View.GONE);
                                Toast.makeText(getApplication(), "个人主页封面更换失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    progress.setVisibility(View.GONE);
                    Toast.makeText(getApplication(), "图片上传失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 刷新
     */
    public void refresh() {
        finish();
        Intent it = new Intent(UserMessageActivity.this, UserMessageActivity.class);
        startActivity(it);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
}